package com.wanxi.service.impl;

import com.wanxi.dto.ProductDTO;
import com.wanxi.dto.ResultDTO;
import com.wanxi.vo.ProductVO;
import com.wanxi.dao.ProductDao;
import com.wanxi.dao.impl.ProductDaoImpl;
import com.wanxi.entity.ProductEntity;
import com.wanxi.service.ProductService;
import com.wanxi.util.Tool;
import org.springframework.beans.BeanUtils;
import redis.clients.jedis.Jedis;

import java.util.List;

public class ProductServiceImpl implements ProductService {

    private ProductDao productDao = new ProductDaoImpl();

    @Override
    public ResultDTO add(ProductVO productVO) {
        int count = productDao.add(getEntity(productVO));
        if (count > 0) {
            Jedis jedis = new Jedis();
            jedis.del("navTitles", "navHrefs");
        }
        return ResultDTO.getResult(count);
    }

    @Override
    public ResultDTO delete(ProductVO productVO) {
        return ResultDTO.getResult(productDao.delete(getEntity(productVO)));
    }

    @Override
    public ResultDTO findById(ProductVO productVO) {
        return ResultDTO.getResult(productDao.findById(getEntity(productVO)));
    }


    @Override
    public ResultDTO findAll(ProductVO productVO) {
        ProductEntity productEntity = new ProductEntity();
        BeanUtils.copyProperties(productVO, productEntity);
        List<ProductEntity> list = productDao.findAll(productEntity);
//        怎么集合Entity转换为DTO？
        List<ProductDTO> productDTOS = Tool.copy(list, ProductDTO.class);
        int count = productDao.count(productEntity);
        return ResultDTO.getResult("", count, productDTOS);
    }

    @Override
    public ResultDTO update(ProductVO productVO) {
        return ResultDTO.getResult(productDao.update(getEntity(productVO)));
    }

    private ProductEntity getEntity(ProductVO productVO) {
        ProductEntity productEntity = new ProductEntity();
        BeanUtils.copyProperties(productVO, productEntity);
        return productEntity;

    }
}
